<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { listNews } from '@/api/news'
import { ElMessage } from 'element-plus'

const router = useRouter()
const newsList = ref([])
const loading = ref(false)

// 分页相关数据
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

// 获取新闻列表
const getNewsList = async () => {
  loading.value = true
  try {
    const res = await listNews({
      page: pagination.value.page,
      size: pagination.value.size
    })
    if (res.code === 200) {
      newsList.value = res.data.list
      pagination.value.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取新闻列表失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 查看新闻详情
const viewNewsDetail = (id) => {
  router.push(`/news/${id}`)
}

// 分页变化处理函数
const handleCurrentChange = (val) => {
  pagination.value.page = val
  getNewsList()
}

const handleSizeChange = (val) => {
  pagination.value.size = val
  pagination.value.page = 1
  getNewsList()
}

onMounted(() => {
  getNewsList()
})
</script>

<template>
  <div class="news-list-container">
    <h2 class="page-title">新闻中心</h2>
    
    <el-card v-loading="loading" class="news-list">
      <div v-for="news in newsList" :key="news.id" class="news-item" @click="viewNewsDetail(news.id)">
        <h3 class="news-title">{{ news.title }}</h3>
        <p class="news-content">{{ news.content }}</p>
        <div class="news-footer">
          <span class="news-time">发布时间：{{ news.publishTime }}</span>
        </div>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.news-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.news-list {
  background: #fff;
}

.news-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: all 0.3s ease;
}

.news-item:last-child {
  border-bottom: none;
}

.news-item:hover {
  background-color: #f5f7fa;
}

.news-title {
  margin: 0 0 10px;
  font-size: 18px;
  color: #303133;
}

.news-content {
  margin: 0 0 10px;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.news-footer {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 